/*
 * 
 *
 *
 */
package com.hboxs.asl.dao.impl;

import com.hboxs.asl.dao.ViewHistoryDao;
import com.hboxs.asl.entity.Member;
import com.hboxs.asl.entity.Product;
import com.hboxs.asl.entity.ViewHistory;
import org.springframework.stereotype.Repository;

import javax.persistence.FlushModeType;
import javax.persistence.NoResultException;
import java.util.List;

/**
 * Dao - 商品浏览记录
 */
@Repository("viewHistoryDaoImpl")
public class ViewHistoryDaoImpl extends BaseDaoImpl<ViewHistory, Long> implements ViewHistoryDao {

    @Override
    public boolean historyExists(Member member, Product product) {
        if (member == null || product == null){
            return false;
        }
        String jpql = "select count(*) from ViewHistory viewHistories where lower(viewHistories.member) = lower(:member) and lower(viewHistories.product) = lower(:product)";
        Long count = entityManager.createQuery(jpql, Long.class).setFlushMode(FlushModeType.COMMIT).setParameter("member", member).setParameter("product", product).getSingleResult();
        return count > 0;
    }


    @Override
    public ViewHistory getViewHistory(Member member, Product product) {
        if (member == null || product == null){
            return null;
        }
        String jpql = "select viewHistories from ViewHistory viewHistories where lower(viewHistories.member) = lower(:member) and lower(viewHistories.product) = lower(:product)";
        try{
            return entityManager.createQuery(jpql, ViewHistory.class).setFlushMode(FlushModeType.COMMIT).setParameter("member", member).setParameter("product", product).getSingleResult();
        }catch(NoResultException e){
            return null;
        }
    }

    @Override
    public List<ViewHistory> getMyViewHistory(Member member) {
        if (member == null){
            return null;
        }
        String jpql = "select viewHistories from ViewHistory viewHistories where lower(viewHistories.member) = lower(:member)";
        try{
            return entityManager.createQuery(jpql, ViewHistory.class).setFlushMode(FlushModeType.COMMIT).setParameter("member", member).getResultList();
        }catch(NoResultException e){
            return null;
        }
    }
}
